package com.luyuan.crm.user.web;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.springframework.stereotype.Component;

import com.ruijie.components.security.model.Role;
import com.ruijie.components.security.service.RoleService;
import com.ruijie.util.StringUtils;

@Component("roleConverter")
public class RoleConverter implements Converter {
    @Resource(name = "roleService")
    private RoleService roleService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (StringUtils.isNullOrEmpty(value)) {
            return null;
        }
        Role role = roleService.getRoleById(value);

        Set<Role> roles = new HashSet<Role>();
        roles.add(role);

        return roles;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof String) {
            return (String) value;
        }
        @SuppressWarnings("unchecked")
        Set<Role> roles = (Set<Role>) value;
        if (roles.isEmpty()) {
            return null;
        }
        return String.valueOf(roles.iterator().next().getRoleName());
    }

}
